/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package course.ya.doc.from.code.model.ast;

import course.ya.doc.from.code.model.statements.AStatement;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 *
 * @author dmitriy
 */
@Entity
@Table(name = "trees")
@SequenceGenerator(sequenceName = "global_seq", name = "global_seq")
@NamedQueries({@NamedQuery(name = "StatementTree.findAll", query = "SELECT t FROM StatementTree t")})
public class StatementTree implements Serializable {

    private static final long serialVersionUID = 163415726952741L;

    @Id
    @Column(name = "tree_id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;

    @ManyToOne(cascade = CascadeType.REMOVE)
    @JoinColumn(name = "tree_root")
    private StatementTreeNode root;

    @Column(name = "tree_name")
    private String name;

    public StatementTree() {
    }

    public StatementTree(String name) {
        this.root = null;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public StatementTreeNode getRoot() {
        return root;
    }

    public void setRoot(StatementTreeNode root) {
        this.root = root;
    }

    public void add(AStatement statement, StatementTreeNode parent) {
        StatementTreeNode newNode = new StatementTreeNode(statement, parent);
        if (parent == null) {
            this.root = newNode;
        } else {
            parent.getChildren().add(newNode);
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || !(obj instanceof StatementTree)) {
            return false;
        }

        StatementTree tree = (StatementTree) obj;
        StatementTreeNode node1 = this.getRoot();
        StatementTreeNode node2 = tree.getRoot();

        if (node1 == null) {
            if (node2 != null) {
                return false;
            } else {
                return true;
            }
        }

        return node1.equals(node2);
    }
}
